<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>网站通讯测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            list-style: none
        }

        body {
            font: 13px Helvetica, Arial;
            height: 100vh;
        }

        #input {
            background: #000;
            padding: 3px;
            bottom: 0;
            width: 100%;
        }

        #input input {
            border: 0;
            padding: 10px;
            width: 90%;
            margin-right: .5%;
        }

        #input button {
            width: 9%;
            background: rgb(130, 224, 255);
            border: none;
            padding: 10px;
            cursor: pointer;
        }

        #messages li {
            padding: 5px 10px;
        }

        #messages li:nth-child(odd) {
            background: #eee;
        }

        #app {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        #app > div:first-child {
            overflow: hidden;
            display: flex;
            flex-grow: 1;
        }

        #user-list {
            float: right;
            width: 20%;
            border-left: 1px solid #000;
            padding-left: 10px;
            min-height: 100%;
            overflow: auto;
        }

        #user-list .media, #message-list .message-left-mes {
            display: flex;
            align-items: center;
            height: 40px;
        }

        #user-list .media-left, #message-list .media-left {
            width: 30px;
            height: 30px;
            border: 1px solid #000000;
            border-radius: 15px;
            margin-right: 10px;
            text-align: center;
            line-height: 30px;
        }

        #user-list .media-body {
            flex-grow: 1;
        }

        #message-list {
            float: left;
            width: 80%;
            min-height: 100%;
            overflow: auto;
        }

        #message-list .media {
            display: flex;
            align-items: center;
        }
    </style>
</head>
<body>
<div id="app">
    <div>
        <ul id="message-list">
            <li v-for="msg in messages">
                <div class="message-left-mes" v-if="msg.type === 'join' || msg.type === 'left'">
                    <div class="media-left">头</div>
                    <div class="media-body">
                        <h4 class="media-heading" v-text="msg.data"></h4>
                    </div>
                </div>
                <div class="message-left-mes" v-if="msg.type === 'chat'">
                    <div class="media">
                        <div class="media-left">头</div>
                        <div class="media-body">
                            <h4 class="media-heading" v-text="msg.user.name"></h4>
                            <span v-text="msg.data"></span>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
        <ul id="user-list">
            <li class="media" v-for="user in users">
                <div class="media-left">头</div>
                <div class="media-body">
                    <h4 class="media-heading" v-text="user.name + ' (' + user.id + ')'"></h4>
                </div>
            </li>
        </ul>
    </div>

    <div id="input">
        <input type="text" v-model="news" @focus="handleinput()" @blur="modalshow()">
        <button @click="startEnd()">Send</button>
    </div>
</div>

</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            messages: [],
            users: [],
            news: null,
            ws: null,
        },
        methods: {
            handleinput: function () {
                let self = this;
                document.addEventListener('keydown', self.implement);
            },
            modalshow: function () {
                let self = this;
                document.removeEventListener('keydown', self.implement);
            },
            implement: function (e) {
                let keynum;
                let keychar;
                keynum = window.event ? e.keyCode : e.which;
                keychar = String.fromCharCode(keynum);
                console.log(keynum + ':' + keychar);
                if (keynum === 13) {
                    console.log('回车');
                    this.startEnd();
                }
            },
            addToUserList: function (user) {
                console.log('users');
                let list = this.users;
                for (let i = 0; i < list.length; i++) {
                    if (list[i].id === user.id) {
                        return;
                    }
                }
                console.log(user);
                this.users.push(user);
            },
            removeFromUserList: function (user) {
                let target = -1;
                let list = this.users;
                for (let i = 0; i < list.length; i++) {
                    if (list[i].id === user.id) {
                        target = i;
                        break;
                    }
                }
                if (target >= 0) {
                    this.users.splice(target, 1);
                }
            },
            addMessage: function (msg) {
                let list = this.messages;
                list.push(msg);
            },
            startEnd: function () {
                console.log('确认');
                let news = this.news;
                let ws = this.ws;
                console.log('[chat] ' + news);
                if (news) {
                    ws.send(news);
                    this.news = null;
                }
            },
            getHref: function (href) {
                let star = href.indexOf('//');
                if (star !== -1) {
                    star = star + 2;
                }
                let end = href.indexOf('/', star);
                return href.substring(star, end);
            }
        },
        created: function () {
            console.log("创建推送连接");
            let href = window.location.href;
            href = this.getHref(href);
            console.log(`ws://${href}/ws/chat`);
            let ws = this.ws = new WebSocket(`ws://${href}/ws/chat`);
            let self = this;
            ws.onmessage = function (event) {
                let data = event.data;
                console.log(data);
                let msg = JSON.parse(data);
                if (msg.type === 'list') {
                    console.log('初始连接');
                    self.users = msg.data;
                } else if (msg.type === 'join') {
                    console.log('有人加入');
                    self.addToUserList(msg.user);
                    self.addMessage(msg);
                } else if (msg.type === 'left') {
                    console.log('有人退出');
                    self.removeFromUserList(msg.user);
                    self.addMessage(msg);
                } else if (msg.type === 'chat') {
                    console.log('聊天信息');
                    self.addMessage(msg);
                }
            };

            ws.onclose = function (evt) {
                console.log(evt);
                console.log('连接关闭');
                console.log(`[reason]${evt.reason}`);
                console.log(`[closed]${evt.code}`);
            };

            ws.onerror = function (code, msg) {
                console.log('连接错误');
                console.log('[ERROR] ' + code + ': ' + msg);
            };

            ws.onopen = function () {
                console.log('连接成功');
            };
        },
        updated: function () {
            document.getElementById('message-list').scrollTop = document.getElementById('message-list').scrollHeight;
        }
    });
</script>